import { BrowserWindow, shell, ipcMain } from 'electron'
import { is } from '@electron-toolkit/utils'
import path from 'path'
import fs from 'fs'
import { join } from 'path'
import icon from '../../resources/icon.png?asset'
import { store } from './index'
let screenSource: any
const tempStreamPath = path.join(__dirname, '../../temp_videos', 'electron_rec_temp.webm')
console.log('tempStreamPath', tempStreamPath)
async function createRecordingVideoWindow(): Promise<BrowserWindow> {
  const width = 420,
    height = 230
  const window = new BrowserWindow({
    width,
    height,
    minHeight: 200,
    minWidth: 220,
    frame: false, // 无边框窗口
    skipTaskbar: false, // 隐藏任务栏图标
    autoHideMenuBar: false, // 隐藏菜单栏
    resizable: true, // 可以调整大小
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      webSecurity: false, // 关闭同源
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  window.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    window.webContents.openDevTools()
    window.loadURL(process.env['ELECTRON_RENDERER_URL'] + '#/viewRecordingVideo')
  } else {
    window.loadURL(join(__dirname, '../../out/renderer/index.html') + '#viewRecordingVideo')
  }
  return window
}
function createRecording(): void {
  // 打开录制窗口
  ipcMain.on('open:recording:video', async (_, payload) => {
    screenSource = payload
    createRecordingVideoWindow()
  })

  ipcMain.handle('get:recording:screen:source', async () => {
    return screenSource
  })

  // 开始录制
  // ipcMain.handle('start:recording:video', async () => {

  // })

  // 停止录制
  // ipcMain.handle('stop-recording:video', () => {

  // })

  // 保存录制
  ipcMain.handle('save:recording:video', (_, arrayBuffer) => {
    return new Promise((resolve) => {
      const buffer = Buffer.from(arrayBuffer)
      const videoFileSaved = store.get('settings').videoFileSaved
      const outputPath = path.join(videoFileSaved, `${Date.now()}.webm`)
      fs.writeFile(outputPath, buffer, (err) => {
        if (err) {
          console.error('保存失败:', err)
          resolve({
            success: false,
            message: '保存失败'
          })
        } else {
          console.log('视频保存成功:', outputPath)
          resolve({
            success: true,
            message: '保存成功',
            path: outputPath
          })
        }
      })
    })
  })

  ipcMain.handle('save:recording:music', (_, arrayBuffer) => {
    return new Promise((resolve) => {
      const buffer = Buffer.from(arrayBuffer)
      const audioFileSaved = store.get('settings').audioFileSaved
      const outputPath = path.join(audioFileSaved, `${Date.now()}.mp4`)
      fs.writeFile(outputPath, buffer, (err) => {
        if (err) {
          console.error('保存失败:', err)
          resolve({
            success: false,
            message: '保存失败'
          })
        } else {
          console.log('音乐保存成功:', outputPath)
          resolve({
            success: true,
            message: '保存成功',
          })
        }
      })
    })
  })

  // 关闭录制窗口
  ipcMain.on('close:win', async (event) => {
    // 关闭窗口
    const win = BrowserWindow.fromWebContents(event.sender)
    win?.close()
  })
}

// function convertToMP4(inputPath: string): void {
//   const outputPath = inputPath.replace('.webm', '.mp4')
//   exec(`ffmpeg -i "${inputPath}" -c:v libx264 -preset fast -crf 22 "${outputPath}"`, (error) => {
//     if (error) {
//       console.error('转换失败:', error)
//       return false
//     } else {
//       console.log('转换成功:', outputPath)
//       fs.unlinkSync(inputPath) // 删除原始webm文件
//       return true
//     }
//   })
// }
export default createRecording
